
<div id="search-result"></div>

<script
    src="https://cdn.bootcdn.net/ajax/libs/art-template/4.13.4/lib/template-web.min.js"
></script>



<script>
  let currentPage = 1;
  let currentKeyword = '';

  function handlePageChange(page) {
    currentPage = page;
    doSearch(currentKeyword);
  }

  async function doSearch(keyword) {
    const pageSize = 10;
    const MAX_PAGES = 10;
    let currentKeyword = keyword;
    if (!keyword) return;

    try {
      const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://127.0.0.1:8090';
      const response = await fetch(
        `${API_BASE_URL}/nice/api/query?query=${encodeURIComponent(keyword)}&page=${currentPage}&size=${pageSize}`
      );
      const data = await response.json();
      
      // 异步加载模板文件
      const templateResponse = await fetch('/nice/static/template/search-result.art');
      const templateContent = await templateResponse.text();
      
      template.defaults.imports.formatRelativeTime = graceUtils.formatRelativeTime;
      const totalPages = Math.min(Math.ceil(data.data.totalElements / pageSize), MAX_PAGES);
      const pages = Array.from({length: totalPages}, (_, i) => i + 1);
      
      if (data.data.content.length === 0) {
        document.getElementById('search-result').innerHTML = '<p class="text-gray-600">未找到相关结果</p>';
      } else {
        const renderedHtml = template.render(templateContent, {
          ...data.data,
          currentPage,
          pages,
          totalPages
        });
        document.getElementById('search-result').innerHTML = renderedHtml;
      }
    } catch (error) {
      console.error('搜索失败:', error);
      document.getElementById('search-result').innerHTML = '<p class="text-red-500">搜索失败，请稍后重试</p>';
    }
  }

  document.addEventListener("DOMContentLoaded", () => {
    const dropdownButton = document.getElementById("dropdown-button-2");
    const dropdownMenu = document.getElementById("dropdown-search-city");
    const options = dropdownMenu.querySelectorAll('button[role="menuitem"]');
    options.forEach((option) => {
      option.addEventListener("click", (e) => {
        e.preventDefault();
        const selectedText = option.textContent.trim();
        dropdownButton.innerHTML =
          selectedText +
          '<svg class="w-2.5 h-2.5 ms-2.5" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 10 6">' +
          '<path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m1 1 4 4 4-4"></path></svg>';
        dropdownMenu.classList.add("hidden");
      });
    });

    // 搜索功能
    const searchForm = document.querySelector('form');
    const searchInput = document.getElementById('location-search');
    
    searchForm.addEventListener('submit', (e) => {
      e.preventDefault();
      const keyword = searchInput.value.trim();
      currentPage = 1;
      doSearch(keyword);
    });
  });
</script>

